<template>
  <div class="role-list">
    <div class="header">
      <h1 class="page-title">角色管理</h1>
      <el-button type="primary" @click="createRole">
        <el-icon><Plus /></el-icon><span>新建角色</span>
      </el-button>
    </div>

    <!-- 搜索 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="关键词">
          <el-input v-model="searchForm.keyword" placeholder="搜索角色名称或编码" clearable style="width: 250px" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon><span>搜索</span>
          </el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 角色列表 -->
    <el-card class="table-card">
      <el-table :data="roleList" v-loading="loading" stripe style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="角色名称" min-width="150" />
        <el-table-column prop="code" label="角色编码" min-width="150" />
        <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 'active' ? 'success' : 'info'">
              {{ row.status === 'active' ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="sortOrder" label="排序" width="100" />
        <el-table-column prop="createdAt" label="创建时间" width="180">
          <template #default="{ row }">{{ formatDate(row.createdAt) }}</template>
        </el-table-column>
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" size="small" @click="editRole(row)">编辑</el-button>
            <el-button link type="success" size="small" @click="assignPermissions(row)">分配权限</el-button>
            <el-button 
              link 
              type="danger" 
              size="small" 
              @click="deleteRole(row)"
              :disabled="isSystemRole(row.code)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.pageSize"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="loadRoles"
        @current-change="loadRoles"
        class="pagination"
      />
    </el-card>

    <!-- 角色表单对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="dialogTitle" 
      width="600px"
      @close="resetForm"
    >
      <el-form 
        ref="formRef" 
        :model="form" 
        :rules="rules" 
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入角色名称" />
        </el-form-item>
        
        <el-form-item label="角色编码" prop="code">
          <el-input v-model="form.code" placeholder="请输入角色编码（英文大写）" :disabled="isEdit" />
        </el-form-item>
        
        <el-form-item label="描述" prop="description">
          <el-input 
            v-model="form.description" 
            type="textarea" 
            :rows="3"
            placeholder="请输入角色描述"
          />
        </el-form-item>
        
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio label="active">启用</el-radio>
            <el-radio label="inactive">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="排序号" prop="sortOrder">
          <el-input-number v-model="form.sortOrder" :min="0" :max="9999" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm" :loading="submitting">确定</el-button>
      </template>
    </el-dialog>

    <!-- 权限分配对话框 -->
    <el-dialog 
      v-model="permissionDialogVisible" 
      title="分配权限" 
      width="600px"
    >
      <el-tree
        ref="permissionTreeRef"
        :data="permissionTree"
        :props="{ children: 'children', label: 'name' }"
        node-key="id"
        show-checkbox
        default-expand-all
        :default-checked-keys="selectedPermissions"
        v-loading="loadingPermissions"
      />
      
      <template #footer>
        <el-button @click="permissionDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitPermissions" :loading="submittingPermissions">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { roleApi, permissionApi } from '@/api/role'
import dayjs from 'dayjs'

const loading = ref(false)
const roleList = ref([])
const dialogVisible = ref(false)
const permissionDialogVisible = ref(false)
const submitting = ref(false)
const submittingPermissions = ref(false)
const loadingPermissions = ref(false)
const isEdit = ref(false)
const currentRole = ref(null)

const searchForm = reactive({
  keyword: ''
})

const pagination = reactive({
  page: 1,
  pageSize: 20,
  total: 0
})

const form = reactive({
  name: '',
  code: '',
  description: '',
  status: 'active',
  sortOrder: 0
})

const permissionTree = ref([])
const selectedPermissions = ref([])
const permissionTreeRef = ref(null)
const formRef = ref(null)

const rules = {
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入角色编码', trigger: 'blur' },
    { pattern: /^[A-Z_]+$/, message: '只能包含大写字母和下划线', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

const dialogTitle = computed(() => isEdit.value ? '编辑角色' : '新建角色')

onMounted(() => {
  loadRoles()
})

const loadRoles = async () => {
  loading.value = true
  try {
    const data = await roleApi.getRoleList({
      page: pagination.page,
      pageSize: pagination.pageSize,
      keyword: searchForm.keyword
    })
    roleList.value = data.items || []
    pagination.total = data.total || 0
  } catch (error) {
    console.error('加载角色列表失败:', error)
    ElMessage.error('加载角色列表失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.page = 1
  loadRoles()
}

const handleReset = () => {
  searchForm.keyword = ''
  handleSearch()
}

const createRole = () => {
  isEdit.value = false
  dialogVisible.value = true
}

const editRole = (role) => {
  isEdit.value = true
  currentRole.value = role
  Object.assign(form, {
    name: role.name,
    code: role.code,
    description: role.description,
    status: role.status,
    sortOrder: role.sortOrder
  })
  dialogVisible.value = true
}

const resetForm = () => {
  formRef.value?.resetFields()
  Object.assign(form, {
    name: '',
    code: '',
    description: '',
    status: 'active',
    sortOrder: 0
  })
}

const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    
    submitting.value = true
    try {
      if (isEdit.value) {
        await roleApi.updateRole(currentRole.value.id, form)
        ElMessage.success('角色更新成功')
      } else {
        await roleApi.createRole(form)
        ElMessage.success('角色创建成功')
      }
      dialogVisible.value = false
      loadRoles()
    } catch (error) {
      console.error('操作失败:', error)
      ElMessage.error(isEdit.value ? '更新失败' : '创建失败')
    } finally {
      submitting.value = false
    }
  })
}

const deleteRole = (role) => {
  ElMessageBox.confirm(`确定要删除角色"${role.name}"吗？`, '警告', {
    type: 'error'
  }).then(async () => {
    try {
      await roleApi.deleteRole(role.id)
      ElMessage.success('删除成功')
      loadRoles()
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error(error.message || '删除失败')
    }
  }).catch(() => {})
}

const assignPermissions = async (role) => {
  currentRole.value = role
  permissionDialogVisible.value = true
  
  loadingPermissions.value = true
  try {
    // 加载权限树
    const tree = await permissionApi.getPermissionTree()
    permissionTree.value = tree || []
    
    // 加载角色已有的权限
    const permissionIds = await roleApi.getRolePermissions(role.id)
    selectedPermissions.value = permissionIds || []
  } catch (error) {
    console.error('加载权限数据失败:', error)
    ElMessage.error('加载权限数据失败')
  } finally {
    loadingPermissions.value = false
  }
}

const submitPermissions = async () => {
  submittingPermissions.value = true
  try {
    // 获取选中的权限ID（包括半选状态）
    const checkedKeys = permissionTreeRef.value.getCheckedKeys()
    const halfCheckedKeys = permissionTreeRef.value.getHalfCheckedKeys()
    const allPermissionIds = [...checkedKeys, ...halfCheckedKeys]
    
    await roleApi.assignPermissions(currentRole.value.id, allPermissionIds)
    ElMessage.success('权限分配成功')
    permissionDialogVisible.value = false
  } catch (error) {
    console.error('权限分配失败:', error)
    ElMessage.error('权限分配失败')
  } finally {
    submittingPermissions.value = false
  }
}

const isSystemRole = (code) => {
  return ['SUPER_ADMIN', 'ADMIN', 'USER'].includes(code)
}

const formatDate = (date) => {
  return date ? dayjs(date).format('YYYY-MM-DD HH:mm:ss') : '-'
}
</script>

<style scoped>
.role-list {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  font-size: 24px;
  margin: 0;
  color: #303133;
}

.search-card {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  justify-content: flex-end;
}
</style>

